<template>
  <!-- 图表容器，必须设置宽高 -->
  <div class="chart-container" ref="chartRef" style="width: 250px; height: 250px; border: 1px solid black;"></div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue';
import * as echarts from 'echarts';


const props = defineProps({
  store: Object
});

const timer = setInterval(() => {
  props.store.getDate({ url: 'api/echart1' })
}, 10000)

// 图表容器DOM引用
const chartRef = ref(null);
// 图表实例
let chartInstance = null;

// 初始化图表
const initChart = () => {
  // 销毁已有实例（防止重复初始化）
  if (chartInstance) {
    chartInstance.dispose();
  }
  // 创建图表实例
  chartInstance = echarts.init(chartRef.value);
  
  // 图表配置
  const option = {
    title: {
      text: props.store.view.data.title.text,
      left: 'center' // 标题居中
    },
    tooltip: {
      trigger: 'axis' // 鼠标 hover 时显示提示
    },
    xAxis: {
      type: props.store.view.data.xAxis.type,
      data: props.store.view.data.xAxis.data
    },
    yAxis: {
      type: props.store.view.data.yAxis.type
    },
    series: props.store.view.data.series
  };

  // 设置配置项并渲染
  chartInstance.setOption(option);
};

// 监听窗口大小变化，自动调整图表尺寸
const handleResize = () => {
  chartInstance?.resize();
};
// 监听数据变化，重新渲染图表
const unwatch = watch(
  () => props.store.view.data,
  () => {
    initChart();
  },
  { deep: true } // 深度监听对象变化
);

// 组件挂载时初始化图表
onMounted(() => {
  // 确保DOM已渲染
  nextTick(() => {
    initChart();
    // 监听窗口 resize 事件
    window.addEventListener('resize', handleResize);
  });
});
// 组件卸载时清理
onUnmounted(() => {
  clearInterval(timer)
  unwatch()
  window.removeEventListener('resize', handleResize);
  chartInstance?.dispose(); // 销毁图表实例，释放资源
});
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 100%; 
}
</style>